package com.bsj.media.init.websocket;

import org.yeauty.pojo.Session;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class UserIdSessionChannelUntil {

    //用户id对应的session
    private static Map<Long, Set<Session>> channelAndIp = new ConcurrentHashMap<>();

    //用户session对应的用户id
    private static Map<Session, Long> mapNetInfo = new ConcurrentHashMap();

    public static Set<Session> gain(Long userId) {
        return channelAndIp.get(userId);
    }

    public static void push(long userId, Session session) {
        Set<Session> sessions = channelAndIp.get(userId);
        if (sessions == null) {
            sessions = new HashSet<>();
        }
        sessions.add(session);
        channelAndIp.put(userId, sessions);
        mapNetInfo.put(session, userId);
    }

    public static void del(Session session) {
        Long userId = mapNetInfo.remove(session);
        if (userId != null) {
            Set<Session> sessions = channelAndIp.get(userId);
            sessions.remove(session);
            if (sessions == null || sessions.isEmpty()) {
                channelAndIp.remove(userId);
            }
        }
    }

}
